#ifndef _h__serve__h_
#define _h__serve__h_
#include "db.hpp"
#include "logerr.hpp"
#include "util.hpp"
#include "session.hpp"
#include "room.hpp"
#include "onlineuser.hpp"
#include "match.hpp"
#endif

#define WWWROOT "./wwwroot"
class gobang_serve
{
private:
    std::string _web_root;
    webserve_t _serve;
    user_table _user;
    online _conn_manage;
    session_manager _session_manager;
    room_manager _room_manager;
    matcher _match_manage;

private:
    void file_handler(webserve_t::connection_ptr &conn)
    {
        // 处理HTTP静态请求
        websocketpp::http::parser::request req = conn->get_request();
        std::string uri = req.get_uri();
        // DBG_LOG("uri=%s", uri.c_str());
        // 访问我们的路径如果是根目录 返回首页
        std::string path;
        std::string root = WWWROOT;
        std::string body;
        if (uri == "/")
        {
            path = root + "/index.html";
        }
        else
        {
            path = root + uri;
        }
        // 下面去访问静态资源
        // DBG_LOG("path=%s", path.c_str());
        bool ret = file_util::read(path, body);
        Json::Value resp;
        if (ret == false)
        {
            // 此时跳转到404页面
            DBG_LOG("读取错误");
            body.clear();
            file_util::read("./wwwroot/404.html", body);
            conn->set_body(body);
            conn->set_status(websocketpp::http::status_code::not_found);
            // conn->append_header("Content-Type", "text/html");
            return;
        }
        // 走到这里访问成功
        conn->set_body(body);
        // conn->append_header("Content-Type", "text/html");
        conn->set_status(websocketpp::http::status_code::ok);
    }
    void http_resp(webserve_t::connection_ptr &conn, bool result,
                   websocketpp::http::status_code::value code, const std::string &reason)
    {
        Json::Value resp_json;
        resp_json["result"] = result;
        resp_json["reason"] = reason;
        std::string resp_body;
        json_util::serialize(resp_json, resp_body);
        conn->set_status(code);
        conn->set_body(resp_body);
        conn->append_header("Content-Type", "application/json");
        return;
    }
    // 注册
    void reg(webserve_t::connection_ptr &conn)
    {
        websocketpp::http::parser::request req = conn->get_request();
        std::string reqbody = req.get_body();
        DBG_LOG("reqbody:%s", reqbody.c_str());
        Json::Value req_json;
        bool ret = json_util::unserialize(reqbody, req_json);
        if (ret == false)
        {
            DBG_LOG("反序列化注册失败");
            // 下面构建应答
            http_resp(conn, false, websocketpp::http::status_code::bad_request, "反序列化失败");
            return;
        }
        if (req_json["username"].isNull() || req_json["password"].isNull())
        {
            DBG_LOG("登录用户名或密码为空");
            http_resp(conn, false, websocketpp::http::status_code::bad_request, "用户名或密码为空");
            return;
        }
        // 下面就是插入数据库
        ret = _user.insert(req_json);
        if (ret == false)
        {
            DBG_LOG("插入数据库失败");
            http_resp(conn, false, websocketpp::http::status_code::bad_request, "用户名已经被注册");
            return;
        }

        return http_resp(conn, true, websocketpp::http::status_code::ok, "用户注册成功");
    }
    void login(webserve_t::connection_ptr &conn)
    {

        websocketpp::http::parser::request req = conn->get_request();
        std::string reqbody = req.get_body();
        // DBG_LOG("reqbody:%s", reqbody.c_str());
        Json::Value req_json;
        bool ret = json_util::unserialize(reqbody, req_json);
        if (ret == false)
        {
            DBG_LOG("反序列化登录失败");
            // 下面构建应答
            http_resp(conn, false, websocketpp::http::status_code::bad_request, "反序列化失败");
            return;
        }
        if (req_json["username"].isNull() || req_json["password"].isNull())
        {
            DBG_LOG("登录用户名或密码为空");
            http_resp(conn, false, websocketpp::http::status_code::bad_request, "用户名或密码为空");
            return;
        }
        // 下面查看在数据库中对比
        ret = _user.login(req_json);
        if (ret == false)
        {
            DBG_LOG("登录失败账户或用户名错误");
            http_resp(conn, false, websocketpp::http::status_code::bad_request, "登录失败账户或用户名错误");
            return;
        }
        // 下面创建我们的session
        uint64_t id = req_json["id"].asInt64();
        // DBG_LOG("%s", std::to_string(id).c_str());
        session_ptr session = _session_manager.create_session(id, LOGIN);
        if (session.get() == nullptr)
        {
            DBG_LOG("创建会话失败");
            return http_resp(conn, false, websocketpp::http::status_code::internal_server_error, "创建会话失败");
        }
        _session_manager.set_session_expire_time(session->get_ssid(), SESSION_TIMEOUT);
        std::string cookie = "SSID=" + std::to_string(session->get_ssid());
        conn->append_header("Set-Cookie", cookie);
        http_resp(conn, true, websocketpp::http::status_code::ok, "登录成功");
        return;
    }
    bool get_cookie_val(const std::string cookie_str, const std::string &key, std::string &val)
    {
        std::vector<std::string> strarr;
        std::string sep = ";";
        string_util::split(cookie_str, sep, strarr);
        for (auto &ch : strarr)
        {
            std::vector<std::string> temarr;
            string_util::split(ch, "=", temarr);
            if (temarr.size() != 2)
                continue;
            if (key == temarr[0])
            {
                val = temarr[1];
                return true;
            }
        }
        return false;
    }
    session_ptr get_session_by_conn(webserve_t::connection_ptr &conn)
    {
        // 获得我们的cookie
        std::string cookiestr = conn->get_request_header("Cookie");
        if (cookiestr.empty())
        {
            return session_ptr();
        }
        // 通过cookie获得我们的ssid
        std::string ssid;
        bool ret = get_cookie_val(cookiestr, "SSID", ssid);
        if (ret == false)
        {
            return session_ptr();
        }
        // 拿到我们的ssid去进行去获取session的句柄
        session_ptr ses = _session_manager.get_session_by_ssid(std::stol(ssid));
        return ses;
    }
    void userinfo(webserve_t::connection_ptr &conn)
    {
        session_ptr ses = get_session_by_conn(conn);
        if (ses.get() == nullptr)
        {
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "登录过期，请重新登录");
        }
        // 拿到session去进行获取用户信息通过uid
        Json::Value user;
        bool ret = _user.select_by_id(ses->get_uid(), user);
        if (ret == false)
        {
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "找不到用户信息，请重新登录");
        }
        std::string body;
        json_util::serialize(user, body);
        conn->set_body(body);
        conn->append_header("Content-Type", "application/json");
        conn->set_status(websocketpp::http::status_code::ok);
        // 4. 刷新session的过期时间
        _session_manager.set_session_expire_time(ses->get_ssid(), SESSION_TIMEOUT);
    }
    // http请求的回调函数 用于处理我们的静态资源 和动态请求如注册 登录 获取用户信息
    void http_callback(websocketpp::connection_hdl hdl)
    {
        webserve_t::connection_ptr conn = _serve.get_con_from_hdl(hdl);
        // 拿到请求
        websocketpp::http::parser::request req = conn->get_request();
        std::string reqmethod = req.get_method();
        std::string requri = req.get_uri();
        // DBG_LOG("reqmethod=%s", reqmethod.c_str());
        // DBG_LOG("requri=%s", requri.c_str());
        if (reqmethod == "POST" && requri == "/reg")
        {
            // DBG_LOG("进入注册处理");
            return reg(conn);
        }
        else if (reqmethod == "POST" && requri == "/login")
        {
            DBG_LOG("进入登录处理");
            return login(conn);
        }
        else if (reqmethod == "GET" && requri == "/userinfo")
        {
            // DBG_LOG("进入获取信息处理");
            return userinfo(conn);
        }
        else // 全是静态页面的请求
        {
            // DBG_LOG("进入静态资源处理");
            return file_handler(conn);
        }
    }
    void wb_reps(webserve_t::connection_ptr &conn, Json::Value &reps)
    {
        std::string reps_str;
        json_util::serialize(reps, reps_str);
        conn->send(reps_str);
    }
    void wsopen_game_hall(webserve_t::connection_ptr &conn)
    {
        // DBG_LOG("进入了游戏大厅的长连接");
        //
        //  我们游戏大厅websocket建立好大厅的调用函数
        //  判断不可以两个用户同时登录
        //  我们要通过session拿到uid
        //  接着加入连接管理模块同时设置我们的session永久
        session_ptr sesptr = get_session_by_conn(conn);
        if (sesptr.get() == nullptr)
        {
            return;
        }

        // 判断是否异地登陆
        Json::Value reps;
        uint64_t uid = sesptr->get_uid();
        // DBG_LOG("uid=%s", std::to_string(uid).c_str());
        if (_conn_manage.is_in_game_hall(uid) == true || _conn_manage.is_in_game_room(uid) == true)
        {
            reps["optype"] = "hall_ready";
            reps["reason"] = "玩家重复登录！";
            reps["result"] = false;
            return wb_reps(conn, reps);
        }
        _conn_manage.enter_game_hall(uid, conn);
        reps["optype"] = "hall_ready";
        reps["result"] = true;
        // 设置我们的session过期时间为永久
        _session_manager.set_session_expire_time(sesptr->get_ssid(), SESSION_FOREVER);
        return wb_reps(conn, reps);
    }

    // 注意如果是同一个浏览器同时发送匹配请求此时的sessionid是一样的谁先进入房间就会导致另一个重复登录
    void wsopen_game_room(webserve_t::connection_ptr &conn)
    {
        // DBG_LOG("进入了房间大厅的长连接");
        Json::Value reps_json;
        // 1.获得客户端信息
        session_ptr ses = get_session_by_conn(conn);
        if (ses == nullptr)
        {
            return;
        }
        // 2.判断该用户是否异地登录
        // DBG_LOG("在房间建立判断uid=%s是不是在大厅或游戏中",std::to_string(ses->get_uid()).c_str());
        if (_conn_manage.is_in_game_hall(ses->get_uid()) || _conn_manage.is_in_game_room(ses->get_uid()))
        {
            reps_json["optype"] = "room_ready";
            reps_json["reason"] = "玩家重复登录！";
            reps_json["result"] = false;
            return wb_reps(conn, reps_json);
        }
        // 3.看一下当前用户是否被分配了房间
        room_ptr room_infor = _room_manager.get_room_by_uid(ses->get_uid());
        if (room_infor.get() == nullptr)
        {
            reps_json["optype"] = "room_ready";
            reps_json["reason"] = "当前用户没有所在的房间！";
            reps_json["result"] = false;
            return wb_reps(conn, reps_json);
        }
        // 4.把用户加入房间管理模块
        _conn_manage.enter_game_room(ses->get_uid(), conn);
        // 5.重新设置我们的session过期时间
        _session_manager.set_session_expire_time(ses->get_ssid(), SESSION_FOREVER);
        reps_json["optype"] = "room_ready";
        reps_json["reason"] = "房间信息获得成功！";
        reps_json["result"] = true;
        reps_json["uid"] = (Json::UInt64)ses->get_uid();
        reps_json["room_id"] = (Json::UInt64)room_infor->get_room_id();
        reps_json["white_id"] = (Json::UInt64)room_infor->get_whiteuser_id();
        reps_json["black_id"] = (Json::UInt64)room_infor->get_blackuser_id();
        return wb_reps(conn, reps_json);
    }

    // websocket建立成功的回调函数
    void wsopen_callback(websocketpp::connection_hdl hdl)
    {
        // 获取我们的大厅界面后开始建立我们的websocket长连接
        // 我们的长连接分为两种
        webserve_t::connection_ptr conn = _serve.get_con_from_hdl(hdl);
        // 拿到请求
        websocketpp::http::parser::request req = conn->get_request();
        std::string requri = req.get_uri();
        if (requri == "/hall")
        {
            // 建立了游戏大厅的长连接
            return wsopen_game_hall(conn);
        }
        else if (requri == "/room")
        {
            // 建立了游戏房间的长连接
            return wsopen_game_room(conn);
        }
    }
    void wsclose_game_hall(webserve_t::connection_ptr &conn)
    {
        // DBG_LOG("进入我们的websocket的断开连接的模块");
        session_ptr ssp = get_session_by_conn(conn);
        if (ssp.get() == nullptr)
        {
            return;
        }
        _conn_manage.exit_game_hall(ssp->get_uid());
        //  设置session的过期的时间
        _session_manager.set_session_expire_time(ssp->get_ssid(), SESSION_TIMEOUT);
    }
    void wsclose_game_room(webserve_t::connection_ptr &conn)
    {
        // 1.获取此时客户端的信息
        session_ptr ssp = get_session_by_conn(conn);
        if (ssp.get() == nullptr)
        {
            return;
        }
        // 2.移出在线用户管理
        _conn_manage.exit_game_room(ssp->get_uid());
        // 3.设置我们的session过期时间
        _session_manager.set_session_expire_time(ssp->get_ssid(), SESSION_TIMEOUT);
        // 4.把当用户移除我们的房间
        _room_manager.remove_room_user(ssp->get_uid()); /*里面会判断如果房间内用户为0房间就会销毁*/
    }
    void wsclose_callback(websocketpp::connection_hdl hdl)
    {
        // 这里也是如果判断关闭的连接是大厅还是room
        webserve_t::connection_ptr conn = _serve.get_con_from_hdl(hdl);
        // 拿到请求
        websocketpp::http::parser::request req = conn->get_request();
        std::string requri = req.get_uri();
        session_ptr ssp = get_session_by_conn(conn);
        if (ssp.get() == nullptr)
        {
            return;
        }
        if (requri == "/hall")
        {
            // 关闭了游戏大厅的长连接
            //
            DBG_LOG("此时是uid=%s离开我们的游戏大厅", std::to_string(ssp->get_uid()).c_str());
            _conn_manage.show_hall();
            wsclose_game_hall(conn);
            DBG_LOG("-------------------------");
            _conn_manage.show_hall();
            return;
        }
        else if (requri == "/room")
        {
            // 关闭了游戏房间的长连接
            wsclose_game_room(conn);
            return;
        }
    }
    void wsmsg_game_hall(webserve_t::connection_ptr &conn, webserve_t::message_ptr &msg)
    {
        // 获取身份信息
        session_ptr ses = get_session_by_conn(conn);
        if (ses.get() == nullptr)
        {
            // DBG_LOG(" wsmsg_game_hall 获取session信息错误");
            return;
        }
        Json::Value req;
        Json::Value reps;
        std::string mes = msg->get_payload();
        DBG_LOG("%s", mes.c_str());
        bool ret = json_util::unserialize(mes, req);
        if (ret == false)
        {
            reps["result"] = false;
            reps["reason"] = "请求信息解析失败";
            wb_reps(conn, reps);
            return;
        }
        if (!req["optype"].isNull() && req["optype"].asString() == "match_start")
        {
            // 我们开始进行匹配
            // DBG_LOG("uid=%s进入了匹配队列",std::to_string(ses->get_uid()).c_str());
            ret = _match_manage.add(ses->get_uid());
            if (ret == false)
            {
                reps["optype"] = "match_start";
                reps["result"] = false;
                reps["reason"] = "加入匹配队列失败";
                wb_reps(conn, reps);
                return;
            }
            reps["optype"] = "match_start";
            reps["result"] = true;
            reps["reason"] = "加入匹配队列成功";
            wb_reps(conn, reps);
            return;
        }
        else if (!req["optype"].isNull() && req["optype"].asString() == "match_stop")
        {
            ret = _match_manage.del(ses->get_uid());
            if (ret == false)
            {
                reps["optype"] = "match_stop";
                reps["result"] = false;
                reps["reason"] = "移除匹配队列失败";
                wb_reps(conn, reps);
                return;
            }
            reps["optype"] = "match_stop";
            reps["result"] = true;
            reps["reason"] = "移除匹配队列成功";
            wb_reps(conn, reps);
            return;
        }

        reps["optype"] = "unknow";
        reps["reason"] = "请求类型未知";
        reps["result"] = false;
        return wb_reps(conn, reps);
    }
    void wsmsg_game_room(webserve_t::connection_ptr &conn, webserve_t::message_ptr &msg)
    {
        // 先获取客户端信息
        session_ptr ses = get_session_by_conn(conn);
        if (ses.get() == nullptr)
        {
            return;
        }
        // 拿到房间信息
        room_ptr roominfor = _room_manager.get_room_by_uid(ses->get_uid());
        Json::Value reps_json;
        if (roominfor.get() == nullptr)
        {
            reps_json["optype"] = "unknow";
            reps_json["reason"] = "没有找到玩家的房间信息";
            reps_json["result"] = false;
            DBG_LOG("房间-没有找到玩家房间信息");
            return wb_reps(conn, reps_json);
        }

        //.接着我们进行获取信息内容
        std::string body = msg->get_payload();
        //.根据信息反序列化
        Json::Value req_json;
        bool ret = json_util::unserialize(body, req_json);
        if (ret == false)
        {
            reps_json["optype"] = "unknow";
            reps_json["reason"] = "room_mesage:反序列化失败";
            reps_json["result"] = false;
            DBG_LOG("房间-没有找到玩家房间信息");
            return wb_reps(conn, reps_json);
        }
        //把请求json串传给我们的room模块
        roominfor->handle_request(req_json);
    }
    void wsmsg_callback(websocketpp::connection_hdl hdl, webserve_t::message_ptr msg)
    {
        // 这里处理来自websocket建立后服务端发的信息
        webserve_t::connection_ptr conn = _serve.get_con_from_hdl(hdl);
        // 拿到请求
        websocketpp::http::parser::request req = conn->get_request();
        std::string requri = req.get_uri();
        // 注意我们收到的uri是hall是我们http时的连接
        // 成为websocket通信好我们的请求和应答都变为了json串
        if (requri == "/hall")
        {
            return wsmsg_game_hall(conn, msg);
        }
        else if (requri == "/room")
        {
            return wsmsg_game_room(conn, msg);
        }
    }

public:
    // 构造函数完成我们的服务器的初始化
    gobang_serve(const std::string &host, const std::string &username, const std::string &password,
                 const std::string &dbname, uint16_t port)
        : _user(host, username, password, dbname, port),
          _session_manager(&_serve),
          _room_manager(&_user, &_conn_manage),
          _match_manage(&_user, &_conn_manage, &_room_manager),
          //_match_manage(&_room_manager, &_user, &_conn_manage),
          _web_root(WWWROOT)
    {
        // 设置websocket的日志
        _serve.set_access_channels(websocketpp::log::alevel::none);
        // 初始化asio中的调度器
        _serve.init_asio();
        _serve.set_reuse_addr(true);
        // 4.设置回调函数
        /*websocket握⼿成功回调处理函数*/
        _serve.set_open_handler(std::bind(&gobang_serve::wsopen_callback, this, std::placeholders::_1));

        /*websocket连接关闭回调处理函数*/
        _serve.set_close_handler(std::bind(&gobang_serve::wsclose_callback, this, std::placeholders::_1));

        /*websocket消息回调处理函数*/
        _serve.set_message_handler(std::bind(&gobang_serve::wsmsg_callback, this, std::placeholders::_1, std::placeholders::_2));

        /*http请求回调处理函数*/
        _serve.set_http_handler(std::bind(&gobang_serve::http_callback, this, std::placeholders::_1));
    }
    void start(int port)
    {
        // 5.设置服务器为监听的端口号
        _serve.listen(port);

        // 获取和客户端的连接
        _serve.start_accept();

        // 启动服务器
        _serve.run();
    }
};
